home *** CD-ROM | disk | FTP | other *** search
- Path: newsfeed.direct.ca!usenet
- From: qjackson@direct.ca
- Newsgroups: comp.lang.c++
- Subject: Re: overloaded operator question
- Date: Fri, 19 Jan 1996 06:22:23 GMT
- Organization: Parsepolis Software
- Message-ID: <4dnd83$i20@grid.direct.ca>
- References: <4dmin1$160@noc2.drexel.edu>
- Reply-To: qjackson@direct.ca
- NNTP-Posting-Host: 204.174.245.127
- X-Newsreader: Forte Free Agent 1.0.82
-
- st918h5w@dunx1.ocs.drexel.edu (Jonathan Juniman) wrote:
-
- >What is wrong with the following declaration:
-
- >MATRIX.H
- >class Matrix
- > {
- > public:
- > // several other functions here...
- > Matrix Matrix::operator *(Matrix&, Matrix&);
- > }
- >
- >My compiler (Microsoft Visual C++ v1.5) complains that there are too
- >many arguments. How can there be too many arguments? * is a binary
- >operator! My intention is to perform matrix multiplication by
- >typing a = b * c, where a, b and c are objects of type Matrix.
-
- Operator overloads only have two parameters when they are outside the
- class. In the case of a = b * c, where b and c are both of the Matrix
- type, there would only be one parameter, as in:
-
- shuString shuString::operator + (const char* pChar)
- {
-
- shuString holder = *this;
- holder.appendString(pChar);
- return holder;
-
- }
-
- In the above example from my shuString class, I have overloaded the +
- operator for:
-
- result = leftarg + rightarg;
-
- where rightarg is shuString and leftarg is char*. Notice the use of
- *this within the function -- it refers to leftarg.
-
- There are two ways to implement overloaded operators: as "friend"
- functions -- that is, outside the class but declared as friends within
- the class interface, or as class functions, that is, within the class.
- Friend functions have two parameters, class functions have one. Most
- classes I've seen use class functions to implement overloads where the
- LEFT arg is an object of class x, whereas they use friend functions to
- implement overloads when the RIGHT arg is of class x.
-
- That said and done, your declaration ought to read:
-
-
-
- class Matrix
- {
- // Foo
- Matrix Matrix::operator* (Matrix&);
- // Bar
- }
-
- and your function ought to read:
-
- Matrix Matrix::operator* (Matrix& rightMatrix)
- {
-
- // You refer to leftMatrix as *this within this function
-
- // Some foo here...
-
- return resultingMatrix;
-
- }
-
- -- \|/ O |
- --+-- Parsepolis Software -*- --|-- Quinn Tyler Jackson
- /|\ "Parse City" /^\ | (aka 'Jamshid')
- >-----------------------------------------------| qjackson@direct.ca
- Ask me about Laleh's Pattern Matcher... |--------------------->
-
-